﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Web.Script.Serialization;

namespace LightSO.Library.Common
{
    /// <summary>
    /// 对象序列化扩展类
    /// </summary>
    public class EnumHelper
    {
        /// <summary>
        /// 枚举扩展方法 读取枚举标记值
        /// </summary>
        /// <param name="val"></param>
        /// <returns></returns>
        public string Text(Enum val)
        {
            Type enumType = val.GetType();
            // 获取枚举常数名称。
            string name = Enum.GetName(enumType, val);
            if (name == null)
                return string.Empty;

            // 获取枚举字段。
            FieldInfo fieldInfo = enumType.GetField(name);
            if (fieldInfo == null)
                return string.Empty;

            // 获取描述的属性。
            TextAttribute attr = Attribute.GetCustomAttribute(fieldInfo,
                typeof(TextAttribute), false) as TextAttribute;

            if (attr != null)
            {
                return attr.Name;
            }

            return val.ToString();
        }
    }

    /// <summary>
    /// 枚举多语言自定义属性类
    /// </summary>
    [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)]
    public class TextAttribute : Attribute
    {
        public TextAttribute()
        {
            
        }

        public TextAttribute(string text, string format = null)
        {
            Name = text;
            Format = format;
        }

        public string Name { get; set; }

        public string Format { get; set; }

        public string Func { get; set; }
    }
}
